import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { cacheConf } from '@conf/cache.conf';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { EACacheService, EAEnvironmentService, ShipperBaseService } from '@shared';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { BankCardManagementService } from '../../../services/bank-card-management.service';

@Component({
  selector: 'app-cwc-withdraw-deposit',
  templateUrl: './withdraw-deposit.component.html',
  styleUrls: ['./withdraw-deposit.component.less']
})
export class CwcAccountManagementWithdrawDepositComponent implements OnInit {
  accountBalance = 0;
  minWithdrawAmount = 0;
  minWithdrawFee: any = 0;
  code = '';
  bankList: Array<any> = [];
  bankAccount = '';
  count = 0;
  interval$: any;
  ui: SFUISchema = {};
  i: any;
  schema: SFSchema = {};
  totalGJ: any = 0.0;
  cacFee: any = 0;
  columns: STColumn[] = [];
  totalBalance = 200;
  bankCardList: Array<any> = [];
  cardNo = '';
  accountDetail: any = {};
  networkTransporterId = '';
  networkTransporterName = '';
  balanceObj: any = {
    allBalance: 99999999
  };
  @ViewChild('st', { static: false }) st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('psd') psd!: ElementRef;
  record: any;
  bankType = '2';

  constructor(
    public service: BankCardManagementService,
    private modal: NzModalRef,
    private shipperSrv: ShipperBaseService,
    public eaCacheSrv: EACacheService,
    public envSrv: EAEnvironmentService,
    public router: Router
  ) {
    this.networkTransporterId = this.eaCacheSrv.get(cacheConf.env)?.networkTransporterId;
  }

  ngOnInit() {
    this.initSF();
    this.getBankList();
    this.getProjectBalanceDetail();
  }




  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        ltdName: {
          title: '网络货运人',
          type: 'string',
          default: this.record?.ltdName,
          ui: {
            widget: 'text',
          }
        },
        bankType: {
          title: '银行',
          type: 'string',
          default: this.bankType,
          enum: [
            { label: '浦发银行', value: '2' }
          ],
          ui: {
            widget: 'select',
            containsAllLabel: false,
            showRequired: true,
            change: (value: any) => {
              // if (value && this.sf?.value?.ltdId) {
              //   const parmas = { bankType: value, ltdId: this.sf.getValue('/ltdId') };
              //   this.getProjectBalanceDetail(parmas);
              // }
            }
          } as SFSelectWidgetSchema
        },
        availableBalance: { title: '可提现余额', type: 'string', ui: { showRequired: false, widget: 'custom' } },
        bankId: {
          title: '提现至',
          type: 'string',
          ui: {
            showRequired: true, widget: 'custom'
          },
        },
        amount: {
          title: '提现金额',
          type: 'string',
          ui: {
            showRequired: true,
            widget: 'custom',
            validator: (val) => {
              if (!val && val !== 0) {
                return [{ keyword: 'required', message: '必填项' }];
              } else if (val > this.balanceObj.allBalance) {
                return [{ keyword: 'required', message: '提现金额超过可提现余额' }];
              }
              return [];
            }
          },

        },
        payPsd: {
          title: '支付密码',
          type: 'string',
          minLength: 6,
          maxLength: 6,
          ui: { widget: 'custom' },
        },
        payPassword: {
          title: '',
          type: 'string',
          ui: {
            hidden: true
          }
        }
      },
      autocomplete: 'off',
      required: ['bankType', 'payPsd']
    };
    this.ui = {
      '*': { spanLabelFixed: 100, grid: { span: 18, gutter: 2 } },
      $addBankCard1: {
        grid: { span: 24 }
      },
      $addBankCard2: {
        grid: { span: 24 }
      }
    };
  }

  save(value: any) {
    if (this.sf.valid) {
      const { amount, bankId, bankType, ltdName, payPassword } = value;
      if (amount > this.balanceObj?.allBalance) {
        this.service.msgSrv.warning('提现金额超过可提现余额！');
        return;
      }
      const params = {
        amount,
        bankId,
        bankType,
        ltdId: this.record.ltdId,
        ltdName,
        payPassword
      };
      this.service.request(this.service.$api_apply_withdraw, { ...params })
        .subscribe(res => {
          if (res) {
            this.service.msgSrv.success('提现成功!');
            this.close(true);
          }
        })
    }
  }
  close(flag: boolean) {
    this.modal.destroy(flag);
  }


  toAddBankPage() {
    window.open(`/#/financial-management/bank-card-management/index?ltdId=${this.record?.ltdId}&ltdName=${this.record?.ltdName}`);
  }
  /**
   * 全部提现
   */
  allWithdrawal() {
    if (!this.sf.getValue('/availableBalance')) {
      this.sf.setValue('/amount', '');
      return;
    }
    this.sf.setValue('/amount', this.balanceObj?.allBalance);
  }
  /**
   * 跳转至忘记密码页
   */
  toForgetPsdPage() {
    window.open('/#/account/edit-paypassword');
  }

  /**
   * 切换银行卡
   */
  checkBankCard(e: any) {
    this.sf.setValue('/bankId', e);
  }
  getBankList() {
    this.service.request(this.service.$api_bank_card_list, { accountType: '3', roleId: this.record?.ltdId }).subscribe((res) => {
      if (res) {
        this.bankCardList = res;
      }
    });
  }

  /**
 * 获取项目账户余额
 */
  getProjectBalanceDetail(params = {}) {
    this.service.request(this.service.$api_get_account_available_balance, { bankType: this.bankType, ltdId: this.record?.ltdId }).subscribe(res => {
      if (res) {
        this.balanceObj = res;
        this.sf.setValue('/availableBalance', res?.allBalance);
        // this.sf.getProperty('/amount')?.updateValueAndValidity();
      }
    })
  }

  keydown(e: any) {
    if (e.keyCode == 37 || e.keyCode == 39) e.preventDefault();
    if (e.keyCode === 8) {
      // const payPswVal = this.sf.getValue('/password');
      // this.sf.setValue('/password', payPswVal.substr(0, payPswVal.length - 1));
    }

  }
  clickInput(e: any) {
    this.psd.nativeElement.focus();
  }
  changePsd(val: any) {
    this.sf.setValue('/payPsd', val);
    if (val || val !== '') {
      const last = val.substr(val.length - 1);
      const password = this.sf.getValue('/payPassword') || '';
      const start = this.psd?.nativeElement.selectionStart;
      const index = val.lastIndexOf('•');
      if (last !== '•') {
        if (password.length !== 0) {
          // 新增 或 替换
          const pre = password.substr(0, index + 1);
          const detail = val.substr(index + 1, val.length);
          this.sf.setValue('/payPassword', pre + detail);
        } else {
          // 新增
          this.sf.setValue('/payPassword', val);
        }
      } else {
        // 删除
        this.sf.setValue('/payPassword', password.substr(0, val.length));
      }
      const payPswVal = this.sf.getValue('/payPsd');
      this.sf.setValue('/payPsd', payPswVal.replace(/./g, "•"));
    } else {
      this.sf.setValue('/payPassword', '');
    }

  }

  /**
   * 设置光标聚焦
   */
  setFocus() {

    const len = this.psd?.nativeElement.value.length;
    this.setSelectionRange(this.psd?.nativeElement, len, len); //将光标定位到文本最后
  }

  /**
   * 设置光标位置
   * @param input dom元素
   * @param selectionStart 起始位置
   * @param selectionEnd 结束位置
   */
  setSelectionRange(input: ElementRef | any, selectionStart: number, selectionEnd: number) {
    if (input?.setSelectionRange) {
      input.focus();
      input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
      var range = input.createTextRange();
      range.collapse(true);
      range.moveEnd('character', selectionEnd);
      range.moveStart('character', selectionStart);
      range.select();
    }
  }


}
